<?php

namespace App\Http\Controllers;

use App\Models\ReservationLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ReservationLogController extends Controller
{
    public function getTimelineEvents(Request $request)
    {
        $start = $request->get("start");
        $end = $request->get("end");

        $model = ReservationLog::query()
            ->with(['projects'])
            ->whereDate('date' , $start)
            ->get();
        $result = [];
        foreach ($model as $value) {
            $timeArr = explode('-',$value['time']);
            $startTime = $timeArr[0];
            $endTime = $timeArr[1];
            $dateStr = $value->date->toDateString();
            foreach ($value->projects as $project) {
                $result[] = [
                    "resourceId" => $project->id,
                    "title" => "{$value['name']} {$value['phone']}",
                    "start" => "$dateStr $startTime",
                    "end" => "$dateStr $endTime",
                ];
            }

        }
        return response()
            ->json($result);
    }

    public function store(Request $request)
    {
        $user = $request->user();
        if (!$user->enable)
            return response()->json([
                'code' => HTTP_AUTH_BLOCK,
                'msg' => 'User get block',
            ]);

        $validator = Validator::make($request->all(), [
            'phone' => 'required|regex:/1[3-9]\d{9}/',
            'project_id' => 'required',
            'time' => 'required',
            'date' => 'required|date',
            'name' => '',
            'remark' => '',
        ], [
            "phone.required" => "预约号码不能为空",
            "phone.regex" => "请输入正确的预约号码",
            "project_id.required" => "预约项目不能为空",
            "time.required" => "预约时间不能为空",
            "date.required" => "预约日期不能为空",
        ]);
        if ($validator->fails()) {
            return response()->json([
                'code' => HTTP_BAD_REQUEST,
                'msg' => $validator->messages()->first(),
            ]);
        }

        $data = $validator->validated();
        $date = $data['date'];

        $reservation = ReservationLog::query()
            ->where("status", 0)
            ->where("user_id", $user->id)
            ->whereDate("date", $date)
            ->exists();
        if ($reservation) {
            return response()->json([
                'code' => HTTP_BAD_REQUEST,
                'msg' => "您当日已经有预约,请按时就诊",
            ]);
        }


        $phone = $data['phone'];
        $time = $data['time'];
        $projects = explode(',', $data['project_id']);
        if ($date && $time && $projects) {
            $date = Carbon::parse($date);
            if (!ReservationLog::checkTimeCanUse($projects, $date, $time))
                return response()->json([
                    'code' => HTTP_BAD_REQUEST,
                    'msg' => "预约上限,请重新选择预约时间!",
                ]);
        }


        $name = data_get($data, 'name');
        $arr = [
            'date' => $date,
            'time' => $time,
            'phone' => $phone,
            'remark' => $data['remark'],
            'name' => $name,
            'user_id' => $user->id,
        ];
        $reservation = ReservationLog::create($arr);
        $reservation->projects()->sync($projects);

        if ($phone !== $user->phone || $name !== $user->name) {
            $user->fill([
                "nike_name" => $name,
                "phone" => $phone,
            ]);
            $user->save();
        }
        return response()->json([
            'code' => HTTP_OK,
            'msg' => "预约成功!",
        ]);
    }

    public function myReservation(Request $request)
    {
        $user = $request->user();
        if (!$user?->enable)
            return response()->json([
                'code' => HTTP_AUTH_BLOCK,
                'msg' => 'User get block',
            ]);

        $date = $request->get('date');
        $date = $date ? Carbon::parse($date): today();
        $reservations = ReservationLog::query()
            ->with(['projects'])
            ->where("status",0)
            ->where('user_id', $user->id)
            ->where("date",'>=', $date->toDateString())
            ->get();

        return response()
            ->json([
                'code' => HTTP_OK,
                'msg' => 'OK',
                'data' => $reservations
            ]);
    }
}
